﻿using B.S.Filtration.Domain;
using B.S.Filtration.ErrorCode;
using B.S.Filtration.Read.Api.Application.Command.ProcessCommand;
using B.S.Filtration.Read.Api.Dto;
using MediatR;
using SqlSugar;

namespace B.S.Filtration.Read.Api.Application.CommandHander.ProcessHandler
{
    public class GetProcedureCommandHandler : IRequestHandler<GetProcedureCommand, APIResult<APIPaging<ProcedureDTO>>>
    {
        private readonly ISqlSugarClient db;

        public GetProcedureCommandHandler(ISqlSugarClient db)
        {
            this.db = db;
        }

        public async Task<APIResult<APIPaging<ProcedureDTO>>> Handle(GetProcedureCommand request, CancellationToken cancellationToken)
        {
            APIResult<APIPaging<ProcedureDTO>> result = new APIResult<APIPaging<ProcedureDTO>>();
            result.code = APIResultCode.success;
            result.msg = "查询显示成功";

            var list = db.Queryable<Procedure, ProcessType>((pd, pt) => new object[]
            {
                JoinType.Inner,pd.ProcessTypeId==pt.ProcessTypeId
            }).Select((pd, pt) => new ProcedureDTO
            {
                ProcedureId = pd.ProcedureId,
                ProcessCode = pd.ProcessCode,
                ProcessName = pd.ProcessName,
                leader = pd.leader,
                Affiliation = pd.Affiliation,
                Status = pd.Status,
                Remark = pd.Remark,
                ProcessTypeId = pt.ProcessTypeId,
                TypeName = pt.TypeName
            });

            int TotalCount = list.Count();
            int TotalPage = (int)Math.Ceiling(TotalCount * 1.0 / request.PageSize);
            list = list.OrderByDescending(pd => pd.ProcedureId).Skip((request.PageIndex - 1) * request.PageSize).Take(request.PageSize);

            APIPaging<ProcedureDTO> paging = new APIPaging<ProcedureDTO>();
            paging.TotalCount = TotalCount;
            paging.TotalPage = TotalPage;
            paging.list = list.ToList();

            result.data = paging;

            return await Task.FromResult(result);
        }
    }
}
